<template>
  <div class="layout_flex">
    <div class="layout_flex_left">
      <el-card class="box-card">
        <el-input v-model="filterTreeValue" placeholder="请输入部门名称" prefix-icon="Search" clearable></el-input>
        <el-divider/>
        <el-tree ref="treeRef" :data="treeList.data" :props="defaultProps" default-expand-all node-key="id"
                 :filter-node-method="filterNode"
                 @node-click="handleNodeClick"/>
      </el-card>
    </div>
    <div class="layout_flex_right">
      <el-form ref="formRef" :model="form.data" inline>
        <el-form-item label="创建时间：">
          <el-date-picker v-model="form.data.date" type="daterange" range-separator="-" start-placeholder="开始时间"
                          end-placeholder="结束时间" @change="changeTime" :clearable="false"/>
        </el-form-item>
        <el-form-item label="用户名称：">
          <el-input v-model="form.data.userName" clearable placeholder="请输入用户名称"
                    style="width: 202px !important;"></el-input>
        </el-form-item>
        <el-form-item label="状态：">
          <el-select v-model="form.data.status" placeholder="请选择" clearable>
            <el-option v-for="item in statusList.data" :key="item.value" :label="item.name" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号：">
          <el-input v-model="form.data.phone" clearable placeholder="请输入手机号"
                    style="width: 202px !important;"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="search">搜索</el-button>
          <el-button icon="Refresh" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="global_operation_wrapper">
        <el-button type="primary" icon="Plus" size="small" plain @click="handAdd">新增</el-button>
        <el-button type="danger" icon="Delete" size="small" plain :disabled="!multipleSelection.data.length > 0"
                   @click="handDelete">
          批量删除
        </el-button>
        <!--                <el-button type="warning" icon="Download" size="small" plain @click="handExport">导出</el-button>-->
      </div>
      <div class="global_table_wrapper">
        <el-table ref="multipleTableRef" :data="dataList.data" highlight-current-row stripe
                  :cell-style="{ textAlign: 'center' }"
                  :header-cell-style="{ textAlign: 'center',background:'#f8f8f9' }"
                  max-height="460" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"/>
          <el-table-column label="用户名称" prop="userName" :show-overflow-tooltip="true"/>
          <el-table-column label="用户昵称" prop="nickname" :show-overflow-tooltip="true"/>
          <el-table-column label="部门" prop="department" :show-overflow-tooltip="true"/>
          <el-table-column label="手机号" prop="phone" :show-overflow-tooltip="true"/>
          <el-table-column label="状态" prop="status" :show-overflow-tooltip="true">
            <template #default="{row}">
              <el-switch v-model="row.status" inline-prompt size="large" active-text="启用" inactive-text="停用"
                         :active-value="1" :inactive-value="0" @change="changeUserStatus(row)"/>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createTime" :show-overflow-tooltip="true"/>
          <el-table-column fixed="right" label="操作" width="300">
            <template #default="{row}">
              <el-button @click="editUser(row)" type="warning" icon="Edit" size="small">编辑</el-button>
              <el-button @click="deleteUser(row)" type="danger" icon="Delete" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <Pagination :total="form.data.total" v-model:page="form.data.pageNo" v-model:limit="form.data.pageSize"
                      @pagination="initialize"/>
        </div>
      </div>
    </div>
  </div>
  <!--  新增/编辑用户弹框-->
  <DialogUser ref="dialogUserRef" :id="dialogUserId" :index="dialogUserIndex" @refresh-the-list="initialize()"/>
</template>

<script setup lang="ts">
import DialogUser from '@/views/system/user/components/dialogUser.vue'
import Pagination from '@/components/Pagination/index.vue'
import dayjs from "dayjs";
import baseRequest from "@/service/baseRequest";
import {ElMessage, ElMessageBox} from "element-plus";

const formRef = ref()
const treeRef = ref()
const multipleTableRef = ref()
let filterTreeValue = ref()
let form = reactive({
  data: {
    id: '',
    date: [],
    startTime: '',
    endTime: '',
    userName: '',
    status: '',
    phone: '',
    pageNo: 1,
    pageSize: 10,
    total: 0
  }
})
let dialogUserId = ref()
let dialogUserIndex = ref()
const dialogUserRef = ref()
let statusList = reactive<{ data: Array<Record<string, string | number>> }>({
  data: [
    {name: '正常', value: 1},
    {name: '停用', value: 0},
  ]
})
const multipleSelection = reactive<{ data: any[] }>({
  data: []
})
let treeList = reactive({
  data: []
})
let dataList = reactive({
  data: []
})
const defaultProps = reactive({
  value: 'id',
  label: 'label',
  children: 'children',
})
const changeTime = (e: any) => {
  if (e && e.length > 0) {
    form.data.startTime = dayjs(e[0]).format('YYYY-MM-DD 00:00:00')
    form.data.endTime = dayjs(e[1]).format('YYYY-MM-DD 23:59:59')
  } else {
    form.data.startTime = ''
    form.data.endTime = ''
  }
}
const search = () => {
  initialize()
}

watch(filterTreeValue, (val) => {
  treeRef.value!.filter(val)
})
const filterNode = (value: string, data: Record<string, any>) => {
  if (!value) return true
  return data.label.includes(value)
}
const handleNodeClick = (data: Record<string, any>) => {
  form.data.id = data.id
  initialize()
}

onMounted(() => {
  getTreeList()
  initialize()
})
const getTreeList = async () => {
  const treeRes = await baseRequest.get('/userGetTree', {})
  treeList.data = treeRes.data.list
}
const initialize = async () => {
  const sendData = JSON.parse(JSON.stringify(form.data))
  delete sendData.date
  const userListRes = await baseRequest.get('/userList', sendData)
  dataList.data = userListRes.data.list
}
//新增用户
const handAdd = () => {
  dialogUserIndex.value = 1
  nextTick(() => {
    dialogUserRef.value.dropDownBoxQuery()
    dialogUserRef.value.dialogComVisible = true
  })
}
//编辑用户
const editUser = (row: Record<string, any>) => {
  dialogUserId.value = row.id
  dialogUserIndex.value = 2
  nextTick(() => {
    dialogUserRef.value.dropDownBoxQuery()
    dialogUserRef.value.backShow()
    dialogUserRef.value.dialogComVisible = true
  })
}
//批量勾选后赋值
const handleSelectionChange = (val: any[]) => {
  multipleSelection.data = val
}
//批量删除
const handDelete = () => {
  if (multipleSelection.data.length > 0) {
    const userNameList = multipleSelection.data.map(item => item.userName)
    ElMessageBox.confirm(
        `确定删除 ${userNameList.join(' , ')} 吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )
        .then(async () => {
          const idList = multipleSelection.data.map(item => item.id)
          const deleteRes = await baseRequest.delete('/deleteUser', {ids: idList}) as any
          if (deleteRes.code == 200) {
            ElMessage.success('删除成功')
            initialize()
          }
        }).catch(() => {
    })
  }
}
//列表开关
const changeUserStatus = async (row: Record<string, any>) => {
  if (row.status == 0) {
    const changeUserRes = await baseRequest.post('/changeUser', {status: 0}) as any
    if (changeUserRes.code == 200) {
      ElMessage.success('停用角色成功')
      initialize()
    }
  } else {
    const changeUserRes = await baseRequest.post('/changeUser', {status: 1}) as any
    if (changeUserRes.code == 200) {
      ElMessage.success('启用角色成功')
      initialize()
    }
  }
}
//行内删除
const deleteUser = (row: Record<string, any>) => {
  ElMessageBox.confirm(
      `确定删除该用户吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        const deleteRes = await baseRequest.delete('/deleteUser', {id: row.id}) as any
        if (deleteRes.code == 200) {
          ElMessage.success('删除成功')
          initialize()
        }
      }).catch(() => {
  })
}
const reset = () => {
  form.data = {
    id: '',
    date: [],
    startTime: '',
    endTime: '',
    userName: '',
    status: '',
    phone: '',
    pageNo: 1,
    pageSize: 10,
    total: 0
  }
  initialize()
}
</script>

<style lang="scss" scoped>
.layout_flex {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .layout_flex_left {
    width: 20%;
    height: 87vh;

    .box-card {
      width: 100%;
      height: 100%;
    }
  }

  .layout_flex_right {
    width: 79%;
    height: 87vh;
  }
}
</style>
